using B.S.Data.ERP.API.Applications.DingDanCommands;
using ERP.Domain;
using ERP.Requst;
using ERP.infratrctrue;
using MediatR;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using System.Text.Json;
using B.S.Data.ERP.API.Applications.WarehouseDealiy.Command;

namespace B.S.Data.ERP.API.Controllers
{
    /// <summary>
    /// 订单控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DingDanController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IBaseRepository<ChuKuInfo> _chuKuRepository;

        public DingDanController(IMediator mediator, IHttpClientFactory httpClientFactory, IBaseRepository<ChuKuInfo> chuKuRepository)
        {
            _mediator = mediator;
            _httpClientFactory = httpClientFactory;
            _chuKuRepository = chuKuRepository;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="command">订单信息</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<APIRequust<int>> AddDingDan(AddDingDanCommand command)
        {
            // 设置创建人信息（假设从用户身份中获取）
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="command">订单更新信息</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<APIRequust<int>> UpdateDingDan(UpdateDingDanCommand command)
        {
            // 设置更新人信息
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<APIRequust<int>> DeleteDingDan(int id)
        {
            var command = new DeleteDingDanCommand { Id = id };
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 查询订单列表
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <returns>订单列表</returns>
        [HttpGet]
        public async Task<APIRequust<List<DingDan>>> QueryDingDan()
        {
            return await _mediator.Send(new QueryDingDanCommand());
        }
        [HttpGet]
        public async Task<IActionResult> GetMes(string sid, int productState,int Num)
        {
            //var http = _httpClientFactory.CreateClient();
            //http.BaseAddress = new Uri("http://localhost:5217/");
            //var condeme =await http.GetAsync("api/Read/GetWarehouse");
            //condeme.EnsureSuccessStatusCode();
            //string codeside = await condeme.Content.ReadAsStringAsync();
            //return Ok(codeside);
            //HttpClient client = new HttpClient()
            //{
            //    BaseAddress = new Uri("http://localhost:5217")
            //};
            //var str = client.GetAsync("/api/Read/GetWarehouse").Result;
            //str.EnsureSuccessStatusCode();
            //var meslist = str.Content.ReadAsStringAsync();
            //return Ok(meslist);
            using (var client = new HttpClient())
            {
                // 构造带查询参数的 URL
                string encodedSid = Uri.EscapeUriString(sid); // 编码特殊字符（如空格、中文）
                string url = $"http://localhost:5217/api/Read/GetWarehouse?SID={encodedSid}";

                // 设置请求头：Authorization（Bearer Token）、Accept
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain")); // 匹配接口的 Accept 要求

                    // 发送 GET 请求
                    HttpResponseMessage response = await client.GetAsync(url);

                    // 确保请求成功（非 2xx 状态会抛 HttpRequestException）
               
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容（接口返回 text/plain，直接读字符串）
                    string responseContent = await response.Content.ReadAsStringAsync();
                
                // 反序列化为对象
                MesApiResponse<Finished_ProductTestDto>? mesResponse = JsonSerializer.Deserialize<MesApiResponse<Finished_ProductTestDto>>(responseContent, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
                
                // 如果反序列化成功且有数据，则保存到ChuKuInfo
                if (mesResponse?.Data != null)
                {
                    var chuKuInfo = new ChuKuInfo
                    {
                        FinisheId = mesResponse.Data.FinisheId,
                        SID = mesResponse.Data.SID,
                        ProductName = mesResponse.Data.ProductName,
                        ProductStandard = mesResponse.Data.ProductStandard,
                        ProductCount =Num,
                        ProductColor = mesResponse.Data.ProductColor,
                        ProductState = mesResponse.Data.ProductState
                    };
                    
                    // 保存到数据库
                    await _chuKuRepository.Add(chuKuInfo);
                }
                
                return Ok(mesResponse);
            }

        }
        [HttpGet]
        public Task<APIRequust<List<ChuKuInfo>>> ShowChukuinfo()
        {
            return _mediator.Send(new ShowWarehouseDealiCommand());
        }

    }
}